package com.ychen.ruijee.common;

/**
 * @author ychen@gotop.cn
 * @date 2024-05-29 23:37
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 * @RestControllerAdvice异常捕获 只捕获 @RestController或@Controller的类。抛出的异常
 */
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    /**
     * 在那些 标有 @RestController 或者 @Controller 的控制器 在处理请求 过程中部 抛出 SQLIntegrityConstraintViolationException异常是
     * GlobalExceptionHandler 类中的 exceptionHandler 方法会被 自动调用
     *
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");

    }
}
